package com.huitone.gddw.service.impl.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huitone.gddw.dao.entity.UserDept;
import com.huitone.gddw.dao.entity.Users;
import com.huitone.gddw.dao.system.IUsersDao;
import com.huitone.gddw.model.support.QueryPage;
import com.huitone.gddw.service.dto.system.UsersDTO;
import com.huitone.gddw.service.system.IUserDeptService;
import com.huitone.gddw.service.system.IUserRoleService;
import com.huitone.gddw.service.system.IUsersService;
import com.huitone.gddw.utils.ContextPropertiesUtils;
//import com.huitone.gddw.utils.MD5Util;
import com.huitone.gddw.utils.SysLoginUtil;

/**
 * 用户管理 接口实现类
 * @author wuluodan
 *
 */
@Service
public class UsersService implements IUsersService {

	@Autowired
	private IUsersDao usersDao;
	
	@Autowired
	private IUserDeptService userDeptService;
	
	@Autowired
	private IUserRoleService userRoleService;
	
	@Override
	public QueryPage<UsersDTO> selectPage(QueryPage<Users> page) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userName", page.getParams().get("userName"));
		map.put("phoneNumber", page.getParams().get("phoneNumber"));
		map.put("deptId", page.getParams().get("deptId"));
		map.put("start", (page.getPageNo() - 1) * page.getPageSize() + 1);
		map.put("end", page.getPageNo() * page.getPageSize());
		List<UsersDTO> result = usersDao.selectPage(map);
		int totalCount = usersDao.selectCount(map);
		
		QueryPage<UsersDTO> queryPage = new QueryPage<UsersDTO>();
		queryPage.setResult(result);
		queryPage.setPageNo(page.getPageNo());
		queryPage.setPageSize(page.getPageSize());
		queryPage.setTotalCount(totalCount);
		return queryPage;
	}
	
	@Override
	public Users getById(String userId) {
		return usersDao.selectByPrimaryKey(userId);
	}
	
	@Override
	public List<Users> getAll() {
		return usersDao.getAll();
	}
	
	@Override
	public UsersDTO toUpdate(String userId) {
		return usersDao.toUpdate(userId);
	}

	@Override
	public void changeStatus(Users entity) {
		this.update(entity);
	}

	@Override
	public void save(Users entity, String deptId) {
//		entity.setPwd(MD5Util.encode(entity.getPwd()));
		this.save(entity);
		
		// 保存用户归属单位
		if (StringUtils.isNotBlank(deptId)) {
			userDeptService.save(entity.getUserId(), deptId);
		}
	}
	
	private void save(Users entity) {
		entity.setInsertTime(new Date());
		entity.setInsertStaffId(SysLoginUtil.getLoginUserId());
		entity.setLastModTime(entity.getInsertTime());
		entity.setLastModStaffId(entity.getInsertStaffId());
		this.initPwdVaildDate(entity);
		usersDao.insertSelective(entity);
	}

	@Override
	public void update(UsersDTO usersDTO) {
		Users user = this.getById(usersDTO.getUserId());
		if (!usersDTO.getPwd().equals(user.getPwd())) {
//			user.setPwd(MD5Util.encode(usersDTO.getPwd()));
			this.initPwdVaildDate(user);
		}
		user.setUserName(usersDTO.getUserName());
		user.setSex(usersDTO.getSex());
		user.setPhoneNumber(usersDTO.getPhoneNumber());
		user.setMailBox(usersDTO.getMailBox());
		user.setRemark(usersDTO.getRemark());
		user.setPwd(usersDTO.getPwd());
		this.update(user);
		
		// 更新用户归属单位
		if (StringUtils.isNotBlank(usersDTO.getDeptId())) {
			UserDept userDept = userDeptService.getByUserId(usersDTO.getUserId());
			// 判断单位是否为空，为空时保存，不空时更新
			if (null == userDept) {
				userDeptService.save(usersDTO.getUserId(), usersDTO.getDeptId());
			} else if (!usersDTO.getDeptId().equals(userDept.getDeptId())) {
				userDept.setDeptId(usersDTO.getDeptId());
				userDeptService.update(userDept);
			}
		}
	}
	
	@Override
	public void update(Users entity) {
		String userId = entity.getUserId();
		try {
			userId = SysLoginUtil.getLoginUserId();
		} catch (Exception e) {
			
		}
		entity.setLastModTime(new Date());
		entity.setLastModStaffId(userId);
		usersDao.updateByPrimaryKey(entity);
	}

	@Override
	public void delete(String userId) {
		userDeptService.delAllByUserId(userId);
		userRoleService.delAllByUserId(userId);
		usersDao.deleteByPrimaryKey(userId);
	}
	
	/**
	 * 获取密码有效期
	 * @param entity Users
	 * @return Users
	 */
	private Users initPwdVaildDate(Users entity) {
		long day = Long.valueOf(ContextPropertiesUtils.getProperty("cryptoperiod"));
		entity.setPwdValidDate(new Date(new Date().getTime() + day * 24 * 60 * 60 * 1000));
		return entity;
	}

	@Override
	public int addFailCount(Users entity) {
		entity.setFailCount(entity.getFailCount() + 1);
		this.update(entity);
		return entity.getFailCount();
	}
	
	@Override
	public void freezeUser(Users entity) {
		entity.setLockStatus(Users.LOCK_STATUS_FREEZE);
		entity.setFreezeDate(new Date());
		this.update(entity);
	}

}
